package com.study.zjh.smartrefreshdemo;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.study.zjh.smartrefreshdemo.bean.ItemBean;

import java.util.List;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {


    private List<ItemBean> mList;

    static class ViewHolder extends RecyclerView.ViewHolder{
        TextView title;
        LinearLayout ll_root;
        public ViewHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.tv_title);
            ll_root = (LinearLayout) itemView.findViewById(R.id.ll_root);
        }
    }

    public MyAdapter(List<ItemBean> list){
        this.mList = list;
    }

    @NonNull
    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item,null);
        final ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyAdapter.ViewHolder viewHolder, final int i) {
        ItemBean bean = mList.get(i);
        viewHolder.title.setText(bean.name);
        viewHolder.ll_root.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(onClickItemListener!=null){
                    onClickItemListener.onClickItemListener(i);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    //下面两个方法提供给页面刷新和加载时调用
    public void add(List<ItemBean> addMessageList) {
        //增加数据
        int position = mList.size();
        mList.addAll(position, addMessageList);
        notifyItemInserted(position);
    }

    public void refresh(List<ItemBean> newList) {
        //刷新数据
        mList.removeAll(mList);
        mList.addAll(newList);
        notifyDataSetChanged();
    }


    private OnClickItemListener onClickItemListener;
    public void setOnClickItemListener(OnClickItemListener onClickItemListener){
        this.onClickItemListener=onClickItemListener;
    }
    public interface OnClickItemListener{
        void onClickItemListener(int pos);
    }
}
